import Vue from "vue";
import VueRouter from "vue-router";
// 一级路由
import Layout from "@/views/layout";
import Login from "@/views/login";
import Register from "@/views/register";
import Detail from "@/views/detail";
import Collect from "@/views/collect";
import Myrent from "@/views/myrent";
// 二级路由
import Home from "@/views/home";
import Find from "@/views/find";
import News from "@/views/news";
import User from "@/views/user";
import City from "@/views/city";

import { getToken } from "@/utils/storage";
import { Toast } from "vant";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      path: "/",
      component: Layout,
      redirect: "/home",
      children: [
        { path: "home", component: Home },
        { path: "find", component: Find },
        { path: "news", component: News },
        { path: "user", component: User },
      ],
    },
    { path: "/login", component: Login },
    { path: "/register", component: Register },
    { path: "/detail", component: Detail },
    { path: "/collect", component: Collect },
    { path: "/myrent", component: Myrent },
    { path: "/city", component: City },
  ],
});

// 路由前置守卫
const whiteList = ["/login", "/register", "/user", "/home", "/find", "/news"];
router.beforeEach((to, from, next) => {
  const token = getToken();
  if (token) {
    next();
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      Toast("身份认证失败");
      next("/login");
    }
  }
});

export default router;
